package com.kun.music.controller;

import com.alibaba.fastjson.JSONObject;
import com.kun.music.domain.Consumer;
import com.kun.music.service.ConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author fangkun
 * @create 2022-12-21-11:45
 */
@RestController
public class ConsumerController {

    @Configuration
    public class MyPicConfig implements WebMvcConfigurer {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/avatorImages/**").addResourceLocations("file:E:\\workSpace\\music-website-master\\music-server\\avatorImages\\");
        }
    }

    @Autowired
    private ConsumerService consumerService;

    //查询所有用户
    @GetMapping("/user")
    public Object allUser(){
        return consumerService.allUser();
    }

    //添加新用户
    @PostMapping("/user/add")
    public Object addUser(HttpServletRequest request){

        JSONObject object = new JSONObject();

        String username = request.getParameter("username").trim();
        String password = request.getParameter("password").trim();
        String sex = request.getParameter("sex").trim();
        String phone_num = request.getParameter("phone_num").trim();
        String email = request.getParameter("email").trim();
        String birth = request.getParameter("birth").trim();
        String introduction = request.getParameter("introduction").trim();
        String location = request.getParameter("location").trim();
        String avator = request.getParameter("avator").trim();

        if (username == null || "".equals(username) || password ==null || "".equals(password)){
            object.put("code",0);
            object.put("msg","用户名或密码不能为空");
            return object;
        }

        Consumer consumer = new Consumer();

        consumer.setUsername(username);
        consumer.setPassword(password);
        consumer.setSex(new Byte(sex));
        consumer.setPhoneNum(phone_num);
        consumer.setEmail(email);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            consumer.setBirth(dateFormat.parse(birth));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        consumer.setIntroduction(introduction);
        consumer.setLocation(location);
        consumer.setAvator(avator);
        consumer.setCreateTime(new Date());
        consumer.setUpdateTime(new Date());

        boolean res = consumerService.addUser(consumer);

        if (res){
            object.put("code",1);
            object.put("msg","添加用户成功");
            return object;
        } else {
            object.put("code",0);
            object.put("msg","添加用户失败");
            return object;
        }

    }

    //删除用户
    @GetMapping("/user/delete")
    public Object deleteUser(HttpServletRequest request){
        String id = request.getParameter("id");
        return consumerService.deleteUser(Integer.parseInt(id));
    }

    //修改用户信息
    @PostMapping("/user/update")
    public Object updateUser(HttpServletRequest request){
        JSONObject object = new JSONObject();

        String id = request.getParameter("id").trim();
        String username = request.getParameter("username").trim();
        String password = request.getParameter("password").trim();
        String sex = request.getParameter("sex").trim();
        String phone_num = request.getParameter("phone_num").trim();
        String email = request.getParameter("email").trim();
        String birth = request.getParameter("birth").trim();
        String introduction = request.getParameter("introduction").trim();
        String location = request.getParameter("location").trim();

        if (username == null || "".equals(username) || password ==null || "".equals(password)){
            object.put("code",0);
            object.put("msg","用户名或密码不能为空");
            return object;
        }

        Consumer consumer = new Consumer();

        consumer.setId(Integer.parseInt(id));
        consumer.setUsername(username);
        consumer.setPassword(password);
        consumer.setSex(new Byte(sex));
        consumer.setPhoneNum(phone_num);
        consumer.setEmail(email);

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            consumer.setBirth(dateFormat.parse(birth));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        consumer.setIntroduction(introduction);
        consumer.setLocation(location);
        consumer.setUpdateTime(new Date());


        boolean res = consumerService.updateUser(consumer);

        if (res){
            object.put("code", 1);
            object.put("msg", "修改成功");
            return object;
        }else {
            object.put("code", 0);
            object.put("msg", "修改失败");
            return object;
        }
    }

    //更新用户头像
    @PostMapping("/user/avatar/update")
    public Object updateUserPic(@RequestParam("file") MultipartFile avatarFile, @RequestParam("id") int id){

            JSONObject jsonObject = new JSONObject();
        //头像为空
        if (avatarFile.isEmpty()){
            jsonObject.put("code","0");
            jsonObject.put("msg","头像上传失败");
            return jsonObject;
        }

        String fileName = System.currentTimeMillis() + avatarFile.getOriginalFilename();
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "music-server" + System.getProperty("file.separator") +"avatorImages" ;

        File file = new File(filePath);
        if (!file.exists()){
            file.mkdir();
        }

        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        String storeAvatorPath = "/avatorImages/"+fileName;

        try {
            avatarFile.transferTo(dest);
            Consumer consumer = new Consumer();
            consumer.setId(id);
            consumer.setAvator(storeAvatorPath);
            consumer.setUpdateTime(new Date());

            boolean res = consumerService.updateUserPic(consumer);

            if (res){
                jsonObject.put("code", 1);
                jsonObject.put("avator", storeAvatorPath);
                jsonObject.put("msg", "上传成功");
                return jsonObject;
            }else {
                jsonObject.put("code", 0);
                jsonObject.put("msg", "上传失败");
                return jsonObject;
            }
        } catch (IOException e){
            jsonObject.put("code", 0);
            jsonObject.put("msg", "上传失败"+e.getMessage());
            return jsonObject;
        }finally {
            return jsonObject;
        }
    }

    @GetMapping("/user/detail")
    public Object getUserById(@RequestParam("id") int id){
        return consumerService.getUserById(id);
    }

    @PostMapping("/user/login/status")
    public Object login(HttpServletRequest request, HttpSession session){
        JSONObject jsonObject = new JSONObject();

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        boolean res = consumerService.login(username,password);

        if (res){
            jsonObject.put("code", 1);
            jsonObject.put("msg", "登录成功");
            jsonObject.put("userMsg", consumerService.loginStatus(username));
            session.setAttribute("username", username);
            return jsonObject;
        }else {
            jsonObject.put("code", 0);
            jsonObject.put("msg", "用户名或密码错误");
            return jsonObject;
        }
    }
}
